import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const Home = () => import('@/views/Home/Home.vue')
const Login = () => import('@/views/Login/Login.vue')
const Layout = () => import('@/views/Layout/Layout.vue')
const UserManage = () => import('@/views/UserManage/UserManage.vue')
const RoleManage = () => import('@/views/RoleManage/RoleManage.vue')
const CommandManage = () => import('@/views/CommandManage/CommandManage.vue')
const Dashboard = () => import('@/views/Dashboard/Dashboard.vue')

const router = new Router({
    mode: 'history',
    routes: [
        {
            path: '/',
            name: 'Home',
            component: Home,
            meta: { requiresAuth: false }
        },
        {
            path: '/login',
            name: 'Login',
            component: Login,
            meta: { requiresAuth: false }
        },
        {
            path: '/dashboard',
            name: 'Layout',
            component: Layout,
            redirect: '/dashboard/welcome',
            meta: { requiresAuth: true },
            children: [
                {
                    path: 'welcome',
                    name: 'Dashboard',
                    component: Dashboard,
                    meta: { title: '欢迎页' }
                },
                {
                    path: 'user',
                    name: 'UserManage',
                    component: UserManage,
                    meta: { title: '用户管理' }
                },
                {
                    path: 'role',
                    name: 'RoleManage',
                    component: RoleManage,
                    meta: { title: '角色管理' }
                },
                {
                    path: 'command',
                    name: 'CommandManage',
                    component: CommandManage,
                    meta: { title: '命令管理' }
                }
            ]
        }
    ]
})

// 路由守卫保持不变
router.beforeEach((to, from, next) => {
    const isAuthenticated = localStorage.getItem('token')
    if (to.meta.requiresAuth && !isAuthenticated) {
        next('/login')
    } else if (to.path === '/login' && isAuthenticated) {
        next('/')
    } else {
        next()
    }
})

export default router